<template>
    <div>
        <el-menu
            default-active="2"
            class="el-menu-vertical-demo"
            router
            @select="change"
        >
            <el-menu-item index="1-2">控制台</el-menu-item>
            <Submenu :list="list"></Submenu>
        </el-menu>
    </div>
</template>
<script setup lang="ts">
import {ref,onMounted} from "vue"
import Submenu from "@/components/home/Submenu.vue"
import {getRightData} from "@/utils/api/right.ts"
import {Righttype} from "@/utils/type/right.d.ts"

import {rightStore} from "@/stores/rights.ts"
const store=rightStore()

let list=ref<Righttype[]>([])

//获取到所有权限
const getRights=async()=>{
    let {data:res}=await getRightData()
    let obj={
        id:112211,
        authName:"用户操作",
        path:"users",
        children: [],
        order:2
    }
    res.data[0].children[0].children.push(obj)
    list.value=res.data

    //获取到叶子节点
    getLeaf(list.value)
    //将叶子节点写入到pinia中
    store.setright(newarr)
}
let newarr=[]
//获取到所有元素的叶子节点
const getLeaf=(arr)=>{
    //遍历list数组  判断是元素的children属性是否为空数组 如果为空 需要将当前元素放入到新数组中  
    //如果不为空 将当前元素传递给本函数调用
    arr.forEach(item=>{
        if(item.children.length==0){
            newarr.push(item)
        }else{
            getLeaf(item.children)
        }
    })
}

onMounted(()=>{
    getRights()
})

//设置选中的数据
const change=(index,indexpath,router)=>{
    // {
    //             title:"中控台",
    //             name:"/welcome",
    //         }
    //console.log(indexpath)
    let key=newarr.findIndex(item=>{
        return item.path==index
    })
    let obj={title:newarr[key].authName,name:"/"+index}
    //判断navs中是否存在当前的title  如果存在改变active  如果不存在追加
    let k=store.navs.findIndex(item=>{
        return item.title==obj.title
    })
    if(k==-1){
        //不存在
        store.setnav(obj)
    }
    store.setActive(obj.name)
    let str=""

    let num=list.value.findIndex(item=>{
            return item.id==indexpath[0]
    })
    str+=list.value[num].authName

    if(indexpath.length>2){
       let n=list.value[num].children.findIndex(it=>{
        return it.id==indexpath[1]
       }) 
       str+="-"+list.value[num].children[n].authName
    }

    str+="-"+obj.title
    store.setBread(str)
}

</script>